package Tree.TraversalByLevel;


import Tree.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class AverageOfLevels {
    public static void main(String[] args) {

    }

    public List<Double> averageOfLevels(TreeNode root){
        List<Double> result = new ArrayList<>();
        if(root == null) return result;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int len = queue.size();
            double sum = 0;
            double average = 0.0;
            for(int i = 0; i < len; i++){
                TreeNode curNode = queue.poll();
                sum += curNode.val;
                if(curNode.left != null) queue.add(curNode.left);
                if(curNode.right != null) queue.add(curNode.right);
            }
            average = sum / len;
            result.add(average);
        }
        return result;
    }
}
